package com.lingx.model.impl.validator;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.lingx.model.IContext;
import com.lingx.model.IPerformer;
import com.lingx.model.IValidator;
import com.lingx.model.impl.AbstractValidator;
import com.lingx.model.impl.DefaultField;
@Component
public class UniqueValidator extends AbstractValidator {
	
	private static final long serialVersionUID = -8725588796516672989L;

	public UniqueValidator() {
		super("UniqueValidator", "唯一验证");
		this.setComment("不需要额外参数");
		this.setMessage(DEFAULT_MESSAGE+"，须唯一不能重复");
	}
	@Resource
	private JdbcTemplate jdbcTemplate;
	@Override
	public boolean valid(Object value,String param,Map<String,Object> params,DefaultField field,IContext context)throws Exception {
		try {
			int c=this.jdbcTemplate.queryForObject("select count(*) from "+context.getEntity().getTableName() +" where "+field.getCode()+"=?",Integer.class,value);
			return c==0;
		} catch (Exception e) {
			return false;
		}
	}

}
